var E_OK			=	1;
var E_ERROR_FORM	=	2;
var E_ERROR_PROC	=	3;

function AsyncForm (formElem)
{
	this.formElem = formElem;
	this.action = formElem.prop("action");

	this.removeMarkers = function()
	{
		this.formElem.find(".message").hide();
		this.formElem.find(".loading-indicator").hide();
		this.formElem.find(".field-error").remove();
	};

	this.getFieldValues = function()
	{
		var values = { };

		this.formElem.find("input[name], select[name], textarea[name]").each(function()
		{
			switch ($(this).attr("type"))
			{
				case "checkbox":
					values[$(this).attr("name")] = $(this).prop("checked") ? ($(this).val() || "1") : "0";
					break;

				default:
					values[$(this).attr("name")] = $(this).val();
					break;
			}
		});

		return values;
	};

	this.setFieldValues = function(values)
	{
		if (!values)
		{
			this.formElem.find("input[name], select[name], textarea[name]").each(function()
			{
				switch ($(this).attr("type"))
				{
					case "hidden":
						break;

					case "checkbox":
						$(this).prop("checked", false);
						break;

					default:
						$(this).val("");
						break;
				}
			});
		}
		else
		{
			this.formElem.find("input[name], select[name], textarea[name]").each(function()
			{
				if (values[$(this).attr("name")] == undefined)
					return;

				switch ($(this).attr("type"))
				{
					case "checkbox":
						$(this).prop("checked", values[$(this).attr("name")] ? true : false);
						break;

					default:
						$(this).val(values[$(this).attr("name")]);
						break;
				}
			});
		}
	};

	this.onFormSubmit = function()
	{
		this.removeMarkers();
		this.formElem.find(".loading-indicator").show();

		Ajax.request (this.action, this.getFieldValues(), this.onDataResult, this);
		return false;
	};

	this.onDataResult = function (r)
	{
		this.formElem.find(".loading-indicator").hide();

		if (r.respuesta == E_OK)
		{
			this.onFormSubmitted (r);
			return;
		}

		if (r.respuesta == E_ERROR_FORM)
		{
			this.formElem.find("input[name], select[name], textarea[name]").each(function()
			{
				var msg = r[$(this).attr("name")];
				if (!msg) return;

				$("<span>").addClass("field-error").text(msg).insertAfter($(this));
			});

			return;
		}

		if (r.respuesta == E_ERROR_PROC)
		{
			this.formElem.find(".message.error").text(r.mensaje).show();
			return;
		}
	};

	this.onFormSubmitted = function (r)
	{
	};

	this.formElem.on("submit", $.proxy (this.onFormSubmit, this));

	this.removeMarkers();
}
